/**
 * author: Hanflyee  flyee1980@163.com
 * vision: v1.0
 * data: 2009-7-9
 */
package com.flyee.controller{
	import com.flyee.controller.timer.DepthTimer;
	import com.flyee.controller.timer.WalkTimer;
	import com.flyee.controller.tools.cartoon.model.AppearanceConfig;
	import com.flyee.model.Charactor;
	import com.flyee.model.Component;
	import com.flyee.service.pool.ObjectCollection;
	import com.flyee.utils.Constants;
	import com.flyee.utils.CoodinateUtil;
	import com.flyee.utils.MyLog;
	import com.flyee.utils.Obsevable;
	import com.flyee.utils.Obsever;
	import com.flyee.utils.gs.TweenMax;
	import com.flyee.viewer.CharactorViewer;
	import com.flyee.viewer.ComponentViewer;
	
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.geom.Point;	
	
	/**
	 * 人物移动的视觉控制器1.3
	 *	人物Viewer使用的是动作图板，通过剪切，得到各个帧和方向的图片
	 *  深度检查采用每100ms检查一次的方式
	 */
	public class CharactorMoveController extends Obsevable implements Obsever{		
		
		/**用于检查人物与人物之间深度关系的计时器*/
		public var depthTimer : DepthTimer = new DepthTimer(100);
						
		public function CharactorMoveController(){
			depthTimer.addEventListener(TimerEvent.TIMER, depthTimer.execute);
		}
		
		public function execute(o : Obsevable, command : String=null, args : * = null) : void {
			switch(command){
				case "playerDie" : 
//					playerDie(args[0]);
					break ;
				default :
					break;
			}
		}
		
		/**场景中添加一个人物*/
		public function addCharactor(charactor : Charactor, charactorViewer : CharactorViewer, scene : Sprite) : void {
			var point : Point = CoodinateUtil.convertToVerticalXY(new Point(charactor.x, charactor.y));			

			scene.addChild(charactorViewer);
			charactorViewer.x = point.x;
			charactorViewer.y = point.y;
			charactor.depth = ObjectCollection.mapData.getDepth(charactor.y + ObjectCollection.currentScene.offsetY, charactor.x);
			checkDepthWithComponent(charactor.depth, charactorViewer);	
		}
		
		/**检查是否同步*/
		public function checkSynchronize(char : Charactor, x : Number, y : Number) : Boolean {
			if(char.x == x && char.y == y)
				return true;
			return false;
		}
		
		/**人物移动*/
		public function move(char : Charactor, charViewer : CharactorViewer, pathArr : Array) : void {
			if(pathArr==null||pathArr.length==0) return ;
			ObjectCollection.master.waitMoveStatus = false;
			var timer : WalkTimer;
			//检查该人物是否已保存了移动TIMER, 如果已保存直接取得, 如果未保存就新建一个并保存
			if(ObjectCollection.moveTimerMap.containsKey(charViewer.vid)){
				timer = ObjectCollection.moveTimerMap.get(charViewer.vid);
				timer.setPath(pathArr);
			}else{
				timer = new WalkTimer(Constants.FRAME_MOVE_TIME);
				ObjectCollection.moveTimerMap.put(charViewer.vid, timer);;
				timer.char = char;
				timer.charViewer = charViewer;
				timer.addEventListener(TimerEvent.TIMER, moveHandler);
				timer.setPath(pathArr);
			}
		}
		
		/**
		 * 对同步，在行走前的位置修正
		 * 在修正完成后，执行行走处理
		 */
		public function synchronizeHandler(char : Charactor, charViewer : CharactorViewer, x : int, y : int, pathArr : Array) : void {
			var p : Point = CoodinateUtil.convertToVerticalXY(new Point(x, y));
			var dir : int = CoodinateUtil.calculateDirection(x - char.x, y - char.y);
			MyLog.debug("同步 "+char.x+":"+char.y+" - "+x+":"+y);
			//播放修正路径动画
			this.setChanged();
			this.notifyObsevers("changeActionDirect", charViewer, AppearanceConfig.MOVE_BY_WALK, dir);
			char.x = x;
			char.y = y;
			char.waitMoveStatus = true;
			var _dx : Number = p.x - charViewer.x;
			var _dy : Number = p.y - charViewer.y;
			var distance : Number = Math.sqrt(_dx*_dx + _dy*_dy);
			TweenMax.to(charViewer
						, distance/Constants.SPEED_SYNCHRONIZE
						, {x:p.x
							, y:p.y
							, onComplete:move
							, onCompleteParams:[char, charViewer, pathArr]});	
		}

		//每一帧的移动处理
		private function moveHandler(event : TimerEvent) : void {
			var timer : WalkTimer = event.target as WalkTimer;
//			changePlate(timer.charViewer, timer.getCurrentDirection());
			var direct : String = "";
			//取得当前方向
			timer.direct = timer.getCurrentDirection();
			//按方向移动, 并保存当前的斜坐标			
			switch(timer.getCurrentDirection()){
				case 0 : 					
					timer.charViewer.x += CoodinateUtil.MIN_WIDTH/2/Constants.STEP_FRAME_COUNT;
					timer.charViewer.y -= CoodinateUtil.MIN_HEIGHT/2/Constants.STEP_FRAME_COUNT;								
					if(timer.frame==0){
						timer.char.y -= 1;
						direct="rightUp";
						timer.delay = 30;
					}
					break ;
				case 1 : 
					timer.charViewer.x += CoodinateUtil.MIN_WIDTH/Constants.STEP_FRAME_COUNT;
					if(timer.frame==0){
						timer.char.y -= 1;
						timer.char.x += 1;
						direct="right";
						timer.delay = 40;
					}
					break ;
				case 2 : 
					timer.charViewer.x += CoodinateUtil.MIN_WIDTH/2/Constants.STEP_FRAME_COUNT;
					timer.charViewer.y += CoodinateUtil.MIN_HEIGHT/2/Constants.STEP_FRAME_COUNT;
					if(timer.frame==0){
						timer.char.x += 1;
						direct="rightDown";
						timer.delay = 30;
					}
					break ;
				case 3 : 
					timer.charViewer.y += CoodinateUtil.MIN_HEIGHT/Constants.STEP_FRAME_COUNT;
					if(timer.frame==0){
						timer.char.y += 1;
						timer.char.x += 1;
						direct="down";
						timer.delay = 30;
					}
					break ;
				case 4 : 
					timer.charViewer.x -= CoodinateUtil.MIN_WIDTH/2/Constants.STEP_FRAME_COUNT;
					timer.charViewer.y += CoodinateUtil.MIN_HEIGHT/2/Constants.STEP_FRAME_COUNT;
					if(timer.frame==0){
						timer.char.y += 1;
						direct="leftDown";
						timer.delay = 30;
					}
					break ;
				case 5 : 
					timer.charViewer.x -= CoodinateUtil.MIN_WIDTH/Constants.STEP_FRAME_COUNT;
					if(timer.frame==0){
						timer.char.y += 1;
						timer.char.x -= 1;
						direct="left";
						timer.delay = 40;
					}
					break ;
				case 6 : 
					timer.charViewer.x -= CoodinateUtil.MIN_WIDTH/2/Constants.STEP_FRAME_COUNT;
					timer.charViewer.y -= CoodinateUtil.MIN_HEIGHT/2/Constants.STEP_FRAME_COUNT;
					if(timer.frame==0){
						timer.char.x -= 1;
						direct="leftUp";
						timer.delay = 30;
					}
					break ;
				case 7 : 
					timer.charViewer.y -= CoodinateUtil.MIN_HEIGHT/Constants.STEP_FRAME_COUNT;
					if(timer.frame==0){
						timer.char.y -= 1;
						timer.char.x -= 1;
						direct="up";
						timer.delay = 30;
					}
					break ;
				default : 					
					break ;	
			}		
			//当移动一个格子的时候	
			if(timer.frame == 0){
				//校正人物图板动作
				this.setChanged();
				this.notifyObsevers("changeActionDirect", timer.charViewer, AppearanceConfig.MOVE_BY_WALK, timer.getCurrentDirection());
				//检查人物与组件的深度关系, 并将人物放到与组件正确的顺序上
				if(timer.char.depth != timer.getCurrentDepth()){
					checkDepthWithComponent(timer.getCurrentDepth(), timer.charViewer);
					timer.char.depth = timer.getCurrentDepth();
				}
				//启动人物与人物深度检查TIMER
				if(!depthTimer.running)
					depthTimer.start();
			}
			//如果主角走到了窗口边缘，地图滚屏
			if(timer.charViewer == ObjectCollection.masterViewer)
				checkMasterLocationInStage(timer.charViewer.x, timer.charViewer.y);
			//TIMER运行下一帧
			timer.nextStep();

		}
		
		/**检查与组件深度*/
		public function checkDepthWithComponent(depth : int, charViewer : CharactorViewer) : void {
			try{
			if(depth == 0){
//				ObjectCollection.currentSceneViewer.componentLayer.setChildIndex(charViewer, ObjectCollection.componentViewerMap.keys().length-1);
				if(ObjectCollection.currentSceneViewer.componentLayer.contains(charViewer))
					ObjectCollection.currentSceneViewer.componentLayer.setChildIndex(charViewer, 0);
				else
					ObjectCollection.currentSceneViewer.componentLayer.addChildAt(charViewer, 0);
			}else{
				//在组件集合中遍历
				for each(var comp : Component in ObjectCollection.componentMap.values()){
					//找到人物与组件对应的深度, 即组件与下一个组件之间
					if(comp.depth == depth)	{
						var vid : String = ObjectCollection.getVidByMid(comp.mid);
						var compViewer : ComponentViewer = ObjectCollection.componentViewerMap.get(vid);
						if(ObjectCollection.currentSceneViewer.componentLayer.contains(charViewer))
							ObjectCollection.currentSceneViewer.componentLayer.removeChild(charViewer);
						var d : int = ObjectCollection.currentSceneViewer
													  .componentLayer
													  .getChildIndex(compViewer);	
						//将人物插到该组件后面
						if(ObjectCollection.currentSceneViewer.componentLayer.contains(charViewer))
							ObjectCollection.currentSceneViewer.componentLayer.setChildIndex(charViewer, d+1);
						else
							ObjectCollection.currentSceneViewer.componentLayer.addChildAt(charViewer, d+1);
//						ObjectCollection.currentSceneViewer
//										.componentLayer
//										.setChildIndex(charViewer, d+1);
//						trace(depth + "    " 
//									+ ObjectCollection.currentSceneViewer.componentLayer.getChildIndex(charViewer) + "   " 
//									+ ObjectCollection.currentSceneViewer.componentLayer.getChildIndex(compViewer));
						break;
					}
				}
			}
			}catch(err:Error){
				trace(err.message);
			}
		}

		/**检查是否滚屏*/
		public function checkMasterLocationInStage(masterX : Number, masterY : Number) : void {
			var directionX : int;
			var directionY : int;
			
			var location : Point = new Point();
			location.x = masterX + ObjectCollection.currentSceneViewer.x;
			location.y = masterY + ObjectCollection.currentSceneViewer.y;
			if(location.x < 100)
				directionX = 1;
			if(location.x + ObjectCollection.masterViewer.width > 1000 - 100)
				directionX = -1;
			if(location.y < 100)
				directionY = 1;
			if(location.y + ObjectCollection.masterViewer.height > 600 - 100)
				directionY = -1;
			if(directionX==0 && directionY==0) return ;
			this.setChanged();
			this.notifyObsevers("scrollWindow", directionX, directionY);
		}
		
		public function pausePlayerMove(charViewer : CharactorViewer) : void {
			var timer : WalkTimer = ObjectCollection.moveTimerMap.get(charViewer.vid);
			if(timer != null){
				timer.pause();
			}
		}

	}
	
}